﻿import com.spikything.utils.SpikyTools;

class com.spikything.utils.KeyListener extends MovieClip {

	// ______________________________________________________
	//
	// CONSTANTS
	// ______________________________________________________
	//
	
	public 	var 	keyPressList 	:Array;
	public 	var  	maxLength 		:Number;
	
	private var 	myListener 		:Object;
	private var 	myCodes 		:Array;
	private var 	container 		:MovieClip;
	
	// ______________________________________________________
	//
	// CONSTRUCTOR
	// ______________________________________________________
	//

	function KeyListener () {};

	// ______________________________________________________
	//
	// EVENT HANDLERS
	// ______________________________________________________
	//

	public function onLoad ():Void { init() };
	public function onUnload ():Void { remove() };

	// ______________________________________________________
	//
	// STATIC METHODS
	// ______________________________________________________
	//

	public static function create (_base:MovieClip,initObj:Object,depth:Number):MovieClip {
		return SpikyTools.createClass(_base,KeyListener,initObj,null,depth);
	}
	
	// ______________________________________________________
	//
	// PRIVATE METHODS
	// ______________________________________________________
	//
	
	public function init ():Void {
		myCodes = [];
		keyPressList = [];
		myListener = new Object();
		delete myListener.onKeyDown;
		myListener.container = this;
		myListener.onKeyDown = function () {
			var mk = container.myCodes;
			var kl = container.keyPressList;
			kl.unshift(Key.getAscii());
			if (maxLength && kl.length>maxLength) kl.pop();
			for (var i in mk) {
				var theCodeObj = mk[i];
				var theCode = theCodeObj[0];
				var theCallback = theCodeObj[1];
				if (kl.slice(0,theCode.length).toString()==theCode.toString()) theCallback.scope[theCallback.func](theCallback.args);
			}
		}
		Key.addListener(myListener);
	}
	
	public function remove ():Void {
		Key.removeListener(myListener);
		this.unloadMovie();
	}

	// ______________________________________________________
	//
	// PUBLIC METHODS
	// ______________________________________________________
	//
	
	public function addTriggerCode (myCode:String, callback:Object):Void {
		var codes = [];
		for (var i=0; i<myCode.length; i++) codes.unshift(myCode.charCodeAt(i));
		myCodes.push([codes,callback]);
	}
	
}